package home

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"minititok/Entities"
	"minititok/Services"
	"net/http"
	"strconv"
	"strings"
)

func getOneselfVideo(c *gin.Context) {
	type GetVideoRequest struct {
		Av   string `json:"av"`
		Time string `json:"time"`
		Uid  string `json:"uid"`
	}
	var body GetVideoRequest
	if err := c.ShouldBindJSON(&body); err != nil {
		_ = c.Error(fmt.Errorf("请求格式错误:" + err.Error()))
		c.JSON(http.StatusBadRequest, gin.H{"customMessage": "请求不正确"})
		return
	}
	watchUser, uerr := c.Get("user")
	if !uerr {
		_ = c.Error(fmt.Errorf("token验证不通过"))
		c.JSON(http.StatusUnauthorized, gin.H{"customMessage": "token验证失败"})
		return
	}
	user, _ := watchUser.(*Entities.User)
	intUid, _ := strconv.Atoi(body.Uid)

	var videos []Entities.Video
	var _ error
	var firstVideo *Entities.Video
	if body.Av != "null" {
		body.Av = strings.TrimPrefix(body.Av, "AV")
		intAv, _ := strconv.Atoi(body.Av)
		firstVideo, _ = Services.FindVideoByAV(int64(intAv))
	}

	currUser, _ := Services.FindUserByUID(intUid)

	videos, _ = Services.GetOneSelfVideoBeforeTime(currUser.Username, body.Time)

	videos = append([]Entities.Video{*firstVideo}, videos...)

	data := gin.H{
		"items":    []gin.H{},
		"has_more": false,
	}
	if len(videos) > 0 {
		if len(videos) > 4 {
			data["has_more"] = true
		} else {
			data["has_more"] = false
		}
		var items []gin.H
		for _, item := range videos {
			intAv := strconv.Itoa(int(item.Av))
			likes, likesErr := Services.EnsureLikes(user.Username, intAv)
			if likesErr != nil {
				_ = c.Error(fmt.Errorf("视频信息错误: %v", likesErr))
				c.JSON(http.StatusUnauthorized, gin.H{"customMessage": "视频信息错误"})
				return
			}
			favorite, favErr := Services.Ensurefavorites(user.Username, intAv)
			if favErr != nil {
				_ = c.Error(fmt.Errorf("视频信息错误: %v", favErr))
				c.JSON(http.StatusUnauthorized, gin.H{"customMessage": "视频信息错误"})
				return
			}
			items = append(items, gin.H{
				"av":       "Av" + strconv.Itoa(int(item.Av)),
				"title":    item.Title,
				"videoUrl": item.VideoURL,
				"author": gin.H{
					"nickname": currUser.Nickname,
					"avatar":   "http://localhost:8000/getAvatar/default.jpg",
					"uid":      currUser.UID,
				},
				"stats": gin.H{
					"likes":       item.Likes,
					"comments":    item.Comments,
					"collects":    item.Collects,
					"views":       item.Views,
					"description": item.Description,
				},
				"createTime":    item.CreateDate,
				"has_likes":     likes.Liked,
				"has_favorites": favorite.Favorited,
			})
		}
		data["items"] = items
	}
	c.JSON(http.StatusOK, data)
}
